/** eslint-disable */
import axios from 'axios';
import type { InternalAxiosRequestConfig, AxiosResponse, AxiosError } from 'axios';

// 定义API响应结构
interface ApiResponse<T = unknown> {
    code: number;
    data: T;
    message: string;
}

// 创建实例
const api = axios.create({
    baseURL: './',
    timeout: 10000,
    headers: {
    'Content-Type': 'application/json',
    },
});

// 请求拦截器 - 使用正确的 InternalAxiosRequestConfig 类型
api.interceptors.request.use(
    (config: InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
    const token = localStorage.getItem('auth_token');
    if (token) {
      // 正确处理 headers 类型
        config.headers = config.headers || axios.defaults.headers;
        config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error: AxiosError): Promise<AxiosError> => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
    (response: AxiosResponse<ApiResponse>): AxiosResponse<ApiResponse>  => {
        return response;
    },
    (error: AxiosError<ApiResponse>): Promise<AxiosError> => {
    if (error.response) {
        console.error('Request failed:', error.response.data.message);
    } else if (error.request) {
        console.error('No response received');
    } else {
        console.error('Request error:', error.message);
    }
    return Promise.reject(error);
    }
);

// 封装请求方法
export const request = {
    get<T = unknown>(url: string, config?: InternalAxiosRequestConfig) {
        return api.get<ApiResponse<T>>(url, config).then(res => res.data);
    },

    post<T = unknown>(url: string, data?: unknown, config?: InternalAxiosRequestConfig) {
        return api.post<ApiResponse<T>>(url, data, config).then(res => res.data);
    },

    put<T = unknown>(url: string, data?: unknown, config?: InternalAxiosRequestConfig) {
        return api.put<ApiResponse<T>>(url, data, config).then(res => res.data);
    },

    delete<T = unknown>(url: string, config?: InternalAxiosRequestConfig) {
        return api.delete<ApiResponse<T>>(url, config).then(res => res.data);
    }
};

export default api;
